#include <stdio.h>
#include "securec.h"
#include "sys/types.h"
#include "sys/stat.h"
#include "sys/ioctl.h"
#include <unistd.h>
#include <fcntl.h>
#include "modbus.h"

int main (int argc,char **argv)
{
    modbus_t *ctx;
    int ret = 0;
    unsigned short speed = 1000, model = 1;

    ctx = modbus_new_rtu("/dev/uartdev-5", 19200, 'N', 8, 1);
    if(modbus_connect(ctx) == -1) {
        printf("Connection failed\n");
        modbus_free(ctx);
        return -1;
    }
    printf("ZBLD.20-120L2R Test \n");

    if(argc == 2 && 0 == strcmp(argv[1], "--help")){
        printf("Usage:\n");
        printf("%s [model] [speed] \n", argv[0]);
        printf("    [model 1:Forward Run 2:Reverse Run]\n");
        printf("    [speed 0~3000 1RPM]\n");
        printf("    eg: %s 1 1000   Positive run speed is 1000\n", argv[0]);
        return 0;
    }

    if(argc == 3){
        speed = atoi(argv[2]);
        model = atoi(argv[1]);
        if(model > 4 || model < 1){
            printf("model  input error\n");
            return 0;
        }
        if(speed < 0 || speed > 3000){
            printf("speed out of range \n");
            return 0;
        }
    }else if(argc > 3){
        printf("Too many parameters \n");
        return 0;
    }

    if(modbus_set_slave(ctx, 1) == 0){
        printf("modbus_set_slave succeed\n");
    }

    ret = modbus_write_register(ctx, 0x2006, 2);//使用modbus通信指令控制
    if(ret == -1){
        printf("Run instruction selection failed\n");
        modbus_free(ctx);
        return -1;
    }

    ret = modbus_write_register(ctx, 0x2007, 3);//使用modbus通信速度控制
    if(ret == -1){
        printf("Velocity given selection failed\n");
        modbus_free(ctx);
        return -1;
    }

    printf("Set rotation speed: speed\n", speed); 
    if(model == 1)
        printf("Set rotation mode: Forward rotation\n");
    else if(model == 2)
        printf("Set rotation mode: Forward Reverse\n");

    ret = modbus_write_register(ctx, 0x2001, speed);//设置速度
    if(ret == -1){
        printf("Set rotation speed failed\n");
        return -1;
    }
    
    char ch = 0;
    printf("please enter E/D/Q:\n");
    while (TRUE)
    {
        // scanf("%c", &ch);
        ch = getchar();
        if(ch == 'D' || ch == 'd'){
            modbus_write_register(ctx, 0x2000, 5);//停止
        }else if(ch == 'E' || ch == 'e'){
            modbus_write_register(ctx, 0x2000, model);
        }else if(ch == 'Q' || ch == 'q'){
            break;
        }
    }
    
    modbus_free(ctx);

    return 0;
}
